<template>
  <div>
    <h1>商品分类列表</h1>
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="名称">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.statusId"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="显示" :value="0" />
            <el-option label="隐藏" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadTypeList">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin-top: 10px">
      <el-button type="primary" @click="onAddType">分类添加</el-button>
    </div>
    <div style="margin-top: 10px">
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        default-expand-all
      >
        <el-table-column prop="typeId" label="ID" sortable />
        <el-table-column prop="typeName" label="名称" sortable />
        <el-table-column prop="typeImage" label="图片" sortable>
          <template #default="scope">
            <el-image
              :src="scope.row.typeImage"
              v-if="scope.row.typeImage != null ? scope.row.typeImage : null"
              style="width: 50px; height: 50px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="typeTop" label="排序" sortable />
        <el-table-column prop="typeStatus" label="状态" sortable>
          <template #default="scope">
            <span v-if="scope.row.typeStatus == 0">显示</span>
            <span v-if="scope.row.typeStatus == 1">隐藏</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" sortable>
          <template #default="scope">
            <el-button type="primary" @click="onAddTypes(scope.row)"
              >添加</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="onEditType(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="onDeleteType(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分类添加 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加类型" width="500">
        <el-form ref="ruleFormRef" :model="form" :rules="rules">
          <el-form-item
            label="分类名称"
            :label-width="formLabelWidth"
            prop="typeName"
          >
            <el-input v-model="form.typeName" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="分类图片"
            :label-width="formLabelWidth"
            prop="typeImage"
          >
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/prod/type/uploadImage"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="headers"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="排序"
            :label-width="formLabelWidth"
            prop="typeTop"
          >
            <el-input-number v-model="form.typeTop" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="状态"
            :label-width="formLabelWidth"
            prop="typeStatus"
          >
            <el-radio-group v-model="form.typeStatus">
              <el-radio :value="0">显示</el-radio>
              <el-radio :value="1">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              添加
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { getTypeList, addType } from "../api/api";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import type { UploadProps } from "element-plus";

const tableData = ref([]);
const searchForm = ref({
  keyWord: "",
  statusId: null,
});

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const ruleFormRef = ref<FormInstance>();
const form = ref({
  typeId: null,
  typeImage: "",
  typeName: "",
  typePid: 0,
  typeStatus: null,
  typeTop: null,
});

const imageUrl = ref("");
const headers = ref({
  token: sessionStorage.getItem("token"),
});
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  //   imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  imageUrl.value = response.data;
};

//校验图片
const checkImage = (rule: any, value: any, callback: any) => {
  if (imageUrl.value == null || imageUrl.value == "") {
    return callback(new Error("请选择图片"));
  } else {
    callback();
  }
};

const rules = reactive<FormRules<any>>({
  typeName: [{ required: true, message: "请输入名称", trigger: "blur" }],
  typeImage: [{ required: true, validator: checkImage, trigger: "blur" }],
  typeTop: [{ required: true, message: "请输入排序", trigger: "blur" }],
  typeStatus: [
    {
      required: true,
      message: "请选择状态",
      trigger: "change",
    },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      form.value.typeImage = imageUrl.value;
      addType(form.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          loadTypeList();
          dialogFormVisible.value = false;
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  form.value = {
    typeId: null,
    typeImage: "",
    typeName: "",
    typePid: 0,
    typeStatus: null,
    typeTop: null,
  };
  imageUrl.value = "";
};

//显示添加一级分类对话框
const onAddType = () => {
  dialogFormVisible.value = true;
  form.value = {
    typeId: null,
    typeImage: "",
    typeName: "",
    typePid: 0,
    typeStatus: null,
    typeTop: null,
  };
  imageUrl.value = "";
};
//显示添加二级分类对话框
const onAddTypes = (row: any) => {
  dialogFormVisible.value = true;
  form.value = {
    typeId: null,
    typeImage: "",
    typeName: "",
    typePid: row.typeId,
    typeStatus: null,
    typeTop: null,
  };
  imageUrl.value = "";
};

const loadTypeList = () => {
  getTypeList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data;
    }
  });
};
onMounted(() => {
  loadTypeList();
});
</script>

<style scoped></style>
<!-- 搜索样式 -->
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
<!-- 图片样式 -->
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
